<template>
    <el-dialog v-if="visible" :title="uploadParams.title" :visible.sync="visible" @opened="handleOpened" :before-close="handleClose" width="440px" append-to-body>
        <el-upload
            ref="upload"
            :multiple="multiple"
            :limit="100"
            :name="uploadParams.name"
            :headers="headers"
            :data="importData"
            :action="uploadUrl"
            :disabled="isUploading"
            :on-progress="handleFileUploadProgress"
            :on-success="handleFileSuccess"
            :on-error="handleFileError"
            :on-exceed="handleExceed"
            :accept="uploadParams.accept"
            auto-upload
            style="padding: 16px; text-align: center"
            drag
        >
            <i class="el-icon-upload"></i>
            <div class="el-upload__text">
                将文件拖到此处，或
                <em>点击上传</em>
            </div>
            <div slot="tip" class="el-upload__tip text-center">
                <span>仅允许导入{{ uploadParams.acceptText }}格式文件。</span>
                <el-link v-if="isShowDownloadTemplate" type="primary" :underline="false" style="font-size: 12px; vertical-align: baseline" @click="handleDownloadTemplate"> 下载模板 </el-link>
            </div>
        </el-upload>
        <div slot="footer" class="dialog-footer">
            <el-button :loading="isUploading" type="primary" @click="handleUploadFile">确 定</el-button>
            <el-button :loading="isUploading" @click="handleClose">取 消</el-button>
        </div>
    </el-dialog>
</template>
<script>
import { getAccessToken, getPlatCode, getTenantCode } from '@/utils/auth';
export default {
    name: 'ZsUpload',
    props: {
        //上传文件所需要的 url 和 title
        uploadParams: {
            type: Object,
            require: true,
            default: () => {
                return {
                    url: '',
                    title: '',
                    data: {},
                    name: 'file',
                    acceptText: '.doc,.docx,.xls,.xlsx,.txt,.ppt,.pptx,.pdf,.jpg,.jpeg,.png,.bmp,.zip',
                    accept: '.doc,.docx,.xls,.xlsx,.txt,.ppt,.pptx,.pdf,.jpg,.jpeg,.png,.bmp,.zip'
                };
            }
        },
        // 是否支持多个文件上传，默认不支持，只允许一次上传一个
        multiple: {
            type: Boolean,
            require: false,
            default: true
        },
        // 显示 和 隐藏 上传文件的弹窗
        visible: {
            type: Boolean,
            require: true,
            default: false
        },
        // 是否显示下载模版
        isShowDownloadTemplate: {
            type: Boolean,
            require: false,
            default: true
        },
        isFolderUpload: {
            type: Boolean,
            require: false,
            default: false
        },
        // 下载模版 所需的参数
        downloadTemplateParams: {
            type: Object,
            require: false,
            default: () => {
                return {
                    url: '',
                    code: '',
                    fileName: ''
                };
            }
        }
    },
    data() {
        return {
            headers: {
                Authorization: getAccessToken(),
                'X-Request-Platform': getPlatCode(),
                'X-Request-Tenant': getTenantCode()
            },
            importData: {},
            isUploading: false,
            uploadUrl: '',

            successNumber: 0, // 上传成功数
            failNumber: 0 // 上传失败数
        };
    },
    mounted() {
        this.importData = this.uploadParams.data;
        console.log(this.importData);
        this.uploadUrl = process.env.VUE_APP_BASE_API + this.uploadParams.url;
    },
    methods: {
        handleExceed(files, fileList) {
            this.$message.warning(`当前限制选择 100 个文件，本次选择了 ${files.length} 个文件，共选择了 ${files.length + fileList.length} 个文件`);
        },
        handleOpened() {
            if (this.isFolderUpload) {
                this.$refs.upload.$children[0].$refs.input.webkitdirectory = true;
            }
        },
        handleDownloadTemplate() {
            this.download(this.downloadTemplateParams.url, { code: this.downloadTemplateParams.code }, this.downloadTemplateParams.fileName);
        },
        // 文件上传中处理
        handleFileUploadProgress(event, file, fileList) {
            this.isUploading = true;
        },
        // 文件上传成功处理
        handleFileSuccess(response, file, fileList) {
            this.isUploading = false;
            // this.$refs.upload.clearFiles();

            /* this.$alert(response.msg, '导入结果', {
                confirmButtonText: '确定',
                callback: action => {
                    this.$emit('close', true);
                    this.dialogVisible = false;
                }
            }); */
            this.$emit('Cback', response);
            response.code === 200 ? this.successNumber++ : this.failNumber++;
            if (this.multiple) {
                if (this.successNumber + this.failNumber === fileList.length) {
                    const info = `共上传${this.successNumber + this.failNumber}个文件，成功 ${this.successNumber}个，失败${this.failNumber}个。`;
                    const errMsg = `<p>${response.msg}</p>`;
                    this.$alert("<div style='overflow: auto;overflow-x: hidden;max-height: 70vh;padding: 10px 20px 0;'>" + info + errMsg + '</div>', '导入结果', { dangerouslyUseHTMLString: true });
                }
            } else {
                this.$alert(response.msg, '导入结果', { dangerouslyUseHTMLString: true });
            }
        },
        // 上传失败
        handleFileError() {
            this.failNumber++;
        },
        // 提交上传文件
        handleUploadFile() {
            this.$emit('close', true);
            this.dialogVisible = false;
            // this.$refs.upload.submit();
        },
        handleClose() {
            if (this.isUploading) {
                return;
            }
            this.dialogVisible = false;
            this.$emit('close', false);
        }
    }
};
</script>

<style lang="scss" scoped></style>
